<template>
  <div>
    <el-upload
      :accept="inputAccept"
      :action="action"
      :before-remove="beforeRemove"
      :before-upload="beforeUpload"
      :class="{ 'hidden-upload': fileList.length >= limit || isUploading }"
      :file-list="fileList"
      :limit="limit"
      :multiple="limit > 1"
      :on-error="handleError"
      :on-exceed="handleExceed"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      class="upload-image"
      ref="upload"
      v-bind="$attrs"
    >
      <el-button
        :size="btnProps.size || 'small'"
        :type="btnProps.type || 'primary'"
        v-bind="btnProps"
        :loading="isUploading"
        >{{ btnText }}</el-button
      >
      <div
        class="el-upload__tip"
        slot="tip"
        style="margin:10px 0"
        v-if="accept"
      >
        {{ desc }}
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" class="img-dialog" width="500px">
      <img :src="dialogImageUrl" width="100%" />
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable no-unused-vars */
import { AliOssClient } from "../../lib/oss";
export default {
  name: "upload-image",
  props: {
    value: {
      type: String,
      default: ""
    },
    url: {
      type: String,
      default: "/imgUpload"
    },
    btnProps: {
      type: Object,
      default: () => ({})
    },
    btnText: {
      type: String,
      default: "点击上传"
    },
    maxSize: {
      type: Number,
      default: 100
    },
    accept: {
      type: String,
      default: ".png,.jpg,.jpeg"
    },
    descText: {
      type: String,
      default: undefined
    },
    limit: {
      type: Number,
      default: 3
    }
  },
  data() {
    return {
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      isUploading: false
    };
  },
  watch: {
    // value: {
    //   handler(val) {
    //     if (val) {
    //       const arr = val.split(";");
    //       console.log(arr);
    //       this.fileList = arr.map(i => ({ url: i }));
    //     } else {
    //       this.fileList = [];
    //     }
    //   }
    // }
  },
  computed: {
    action() {
      return (
        process.env.VUE_APP_API_PREFIX_URL +
        process.env.VUE_APP_UPLOAD_URL +
        this.url
      );
    },
    desc() {
      return (
        this.descText ||
        `支持格式：${this.accept} ，单个文件不能超过${this.maxSize}Kb，最多上传个数：${this.limit} 。`
      );
    },
    inputAccept() {
      return this.accept.replace(".", "image/");
    }
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleExceed(files, fileList) {
      this.handleWarning(`只能选择 ${this.limit} 个文件`);
    },

    async beforeUpload(file) {
      const { size, type, name } = file;
      const ret = this.checkFileType(name) && this.checkFileSize(size);
      if (ret) {
        this.isUploading = true;
        try {
          let res = await AliOssClient.upload(file);
          this.isUploading = false;
          this.$emit("input", res.url);
        } catch (error) {
          this.isUploading = false;
        }
      }
      return Promise.reject();
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${file.name}？`);
    },
    clearFiles() {
      this.$refs.upload.clearFiles();
    },
    handleError() {
      this.isUploading = false;
      console.log("upload Error");
      this.$message({
        type: "error",
        message: "上传失败！"
      });
    },
    async handleSuccess(res, file, fileList) {
      // this.isUploading = false;
      // const arr = fileList.map(i => (i.response ? i.response.data : i.url));
      // const ret = arr.join(";");
      // this.$emit("change", ret);
      // this.$emit("input", ret);
    },
    handleRemove(file, fileList) {
      // const ret = fileList.map(i => i.url).join(";");
      // this.$emit("change", ret);
      // this.$emit("input", ret);
    },
    checkFileType(name) {
      const t = name.substring(name.lastIndexOf("."));
      if (this.accept.split(",").filter(i => i === t).length === 0) {
        this.handleWarning(`上传文件只能是 ${this.accept} 格式!`);
        return false;
      }
      return true;
    },
    checkFileSize(size) {
      if (size > 1024 * this.maxSize) {
        this.handleWarning(`上传文件大小不能超过 ${this.maxSize} Kb!`);
        return false;
      }
      return true;
    }
  }
};
</script>
<style lang="scss" scoped>
.upload-image {
  overflow: hidden;
}

// 去掉upload 动画效果
/deep/.el-upload-list__item {
  transition: none !important;
}
/deep/.hidden-upload {
  .el-upload--picture-card {
    display: none !important;
  }
}
.el-upload__tip {
  line-height: 1.2;
  margin: 0;
  color: #e6a23c;
}
</style>
